package com.silentfish.core.util.data;

import com.ibatis.common.beans.Probe;
import com.ibatis.common.beans.ProbeFactory;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

public class CollectionUtil extends CollectionUtils{

    private static final Probe PROBE = ProbeFactory.getProbe();

    //todo 以下几个方法 可能开发就是需要返回null值 如当为sum(消费金额)为null则返回0 思考怎么方便 不需要和需要 返回 的两种情况

    /**
     *
     */
    @SuppressWarnings("unchecked")
    public static <E, K> List<K> getValueList(List<E> list, String valueProp) {

        List<K> valueList = new ArrayList<>();

        if (CollectionUtils.isNotEmpty(list)) {

            list.removeAll(Collections.singleton(null));

            for (E e : list) {

                K value = (K) PROBE.getObject(e, valueProp);
                if (value != null) valueList.add(value);

            }

        }

        return valueList;
    }

    /**
     *
     */
    @SuppressWarnings("unchecked")
    public static <K, V, E> Map<K, V> listforMap(List<E> list, String keyProp, String valueProp) {

        Map<K, V> map = new LinkedHashMap<>();

        if (CollectionUtils.isNotEmpty(list)) {

            list.removeAll(Collections.singleton(null));

            for (E object : list) {

                K key = (K) PROBE.getObject(object, keyProp);
                V value = (V) ((StringUtils.isEmpty(valueProp))?(object):(PROBE.getObject(object, valueProp)));
                if (value != null) map.put(key, value);

            }

        }

        return map;
    }

    /**
     *
     */
    @SuppressWarnings("unchecked")
    public static <K, V, E> Map<K, List<V>> listforListMap(List<E> list, String keyProp, String valueProp) {

        Map<K, List<V>> map = new LinkedHashMap<>();

        if (CollectionUtils.isNotEmpty(list)) {

            list.removeAll(Collections.singleton(null));

            for (E object : list) {

                K key = (K) PROBE.getObject(object, keyProp);
                V value = (V) ((StringUtils.isEmpty(valueProp))?(object):(PROBE.getObject(object, valueProp)));

                List<V> values = map.get(key);
                if (values == null) {
                    values = new ArrayList<>();
                    map.put(key, values);
                }

                values.add(value);

            }

        }
        return map;
    }

//    public <T> void sort(Collection<T> collection, String... keys){//todo 最好支持根据多字段排序
//
//        Collections.sort(collection, new Comparator<T>() {
//
//            @Override
//            public int compare(T o1, T o2) {
//                return o1.getAttributeId().compareTo(o2.getAttributeId());
//            }
//
//        });
//
//    }
}